import { Injectable } from '@nestjs/common';
import fs = require('fs');
import path = require('path');

function getFileListByRecursion(dir, list) {
  let files = fs.readdirSync(dir);
  for (const item of files) {
    if (item.startsWith('_')) {
      continue;
    }
    let fPath = path.join(dir, item);
    let stat = fs.statSync(fPath);
    if (stat.isDirectory()) {
      getFileListByRecursion(fPath, list);
      list.push({fn: fPath, s: 'd'});
    } else if (stat.isFile()) {
      list.push({fn: fPath, s: '-'});
    } else if (stat.isSymbolicLink()) {
      list.push({fn: fPath, s: 'l'});
    }
  }
  return list;
}

function getFileListByDetail(dir, list) {
  let files = fs.readdirSync(dir);
  for (const item of files) {
    if (item.startsWith('_')) {
      continue;
    }
    let fPath = path.join(dir, item);
    let stat = fs.statSync(fPath);
    if (stat.isDirectory()) {
      list.push({fn: fPath, s: 'd'});
    } else if (stat.isFile()) {
      list.push({fn: fPath, s: '-', fs: stat.size});
    } else if (stat.isSymbolicLink()) {
      list.push({fn: fPath, s: 'l'});
    }
  }
  return list;
}

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
  
  getListByRecursion(filename: string): string[] {
    return getFileListByRecursion(path.join(process.env.KFTP_ROOT + filename), []).map((item) => {
      item['fn'] = item['fn'].substring(process.env.KFTP_ROOT.length, item['fn'].length);
      return item;
    });
  }

  getListByDetail(filename: string): string[] {
    return getFileListByDetail(path.join(process.env.KFTP_ROOT + filename), []).map((item) => {
      item['fn'] = item['fn'].substring(process.env.KFTP_ROOT.length, item['fn'].length);
      return item;
    });
  }

  getFile(filename: string) {
    try {
      if (!fs.existsSync(path.join(process.env.KFTP_ROOT + filename))) {
	throw 'No such file or directory';
      }
      return fs.createReadStream(path.join(process.env.KFTP_ROOT + filename));
    } catch (e) {
      throw e;
    }
  }
}
